@page "/checkout"
@inject OrderState OrderState
@inject HttpClient HttpClient
@inject NavigationManager NavigationManager
@implements IDisposable

<div class="main">
    <EditForm EditContext=editContext OnValidSubmit=PlaceOrder>
        <div class="checkout-cols">
            <div class="checkout-order-details">
                <h4>Review order</h4>
                <OrderReview Order="Order" />
            </div>

            <div class="checkout-delivery-address">
                <h4>Deliver to...</h4>
                @if (isError)
                {
                    <div class="alert alert-danger">Please enter a vaild name and address.</div>
                }
                <AddressEditor Address="Order.DeliveryAddress" />
            </div>
        </div>

        <button class="checkout-button btn btn-warning" type="Submit" disabled=@isError>
            Place order
        </button>

        <DataAnnotationsValidator />
    </EditForm>
</div>

@code {
    Order Order => OrderState.Order;

    bool isError = true;
    EditContext? editContext;

    protected override void OnInitialized()
    {
        editContext = new(Order.DeliveryAddress);
        editContext.OnFieldChanged += HandleFieldChanged;
    }

    async Task PlaceOrder()
    {
        var response = await HttpClient.PostAsJsonAsync(
            $"{NavigationManager.BaseUri}orders", OrderState.Order);
        var newOrderId = await response.Content.ReadFromJsonAsync<int>();

        OrderState.ResetOrder();
        NavigationManager.NavigateTo($"myorders/{newOrderId}");
    }

    void HandleFieldChanged(object? sender, FieldChangedEventArgs e)
    {
        isError = editContext?.Validate() is false;
        StateHasChanged();
    }

    public void Dispose()
    {
        if (editContext is null) return;
        editContext.OnFieldChanged -= HandleFieldChanged;
    }
}